#!/bin/python3

import os
import sys
import time

#*******************config********************#
#本地存放备份文件的路径
tar_file_path="/a-boat/backup/"
#备份文件前缀
tar_prefix="boat-bak-"
#保留几个版本的备份文件
tar_version_n=3
#用户指定需要备份的文件，此文件放在用户家目录下
user_bkfile_name="auto-bk.list"
#存放备份文件的远程服务器 可为空 
    #需要确保执行脚本的用户可以免密登陆backupserver
backupserver="root@u-cloud:/mnt/user/boat-backup/"
#*****************end config******************#

autobacks = []
backpaths = []
if not tar_file_path.endswith("/"):
    tar_file_path = tar_file_path + "/"

if not os.path.isdir(tar_file_path):
    os.makedirs(tar_file_path)
    print("@ make {} dir".format(tar_file_path))

users = os.listdir("/home/")
#找到所有的auto-bk.list文件
for user in users:
    path="/home/{}/".format(user)
    if os.path.isdir(path):
        path = path + "auto-bk.list"
        if os.path.isfile(path):
            autobacks.append(path)

print("@ ##auto list:");
print(autobacks)

#解析auto-bk.list文件
for backlist in autobacks:
    file = open(backlist, mode='r');

    backlist = backlist[:-12]

    while True:
        path1 = file.readline();
        if not path1:
            break;

        if(path1.startswith("#")):
            print("skip {}".format(path1));
            continue
        if(path1.startswith("./")):
            path1 = path1[2:]
        tmp = backlist + path1
        tmp = tmp.strip();
        print(tmp);
        if os.path.isdir(tmp) or os.path.isfile(tmp):
            backpaths.append(tmp);

print("@ ##back path:");
print(backpaths)

backtar = "boat-bak-{}.tar.bz".format(time.strftime("%Y-%m-%d-%H_%M_%S"));
print("@ tar: "+backtar)

tarcmd = "tar -jvcf {}{} ".format(tar_file_path, backtar)

for path in backpaths:
    tarcmd += path;
    tarcmd += " "
    tarcmd.strip("\n");

print(tarcmd);

os.system(tarcmd);

# start clean
#os.system("/a-boat/boat-bak-clean.sh")

tars = os.listdir(tar_file_path)
if not tars:
    exit(0)
else:
    #按日期排序文件
    tars = sorted(tars, key=lambda x: os.path.getmtime(os.path.join(tar_file_path, x)))

if len(tars) > tar_version_n:
    tars_rm = tars[0:len(tars)-tar_version_n]
    for tar in tars_rm:
        os.remove(tar_file_path+tar)
        print("@ remove old version: {}".format(tar_file_path+tar));

if (len(backupserver) > 3) and (len(tars) > 0):
    #  os.system("scp {}{} {}".format(tar_file_path, backtar, backupserver))
    #print("scp {}{} {}".format(tar_file_path, backtar, backupserver))
    os.system("rsync -a --delete {} {}".format(tar_file_path, backupserver))

